package com.terra.ns.imp.common.sms

import cn.hutool.json.JSONUtil
import com.aliyun.dysmsapi20170525.Client
import com.aliyun.dysmsapi20170525.models.SendSmsRequest
import com.aliyun.teaopenapi.models.Config
import com.terra.ns.imp.common.core.exception.BaseException
import com.terra.ns.imp.common.sms.config.SmsProperties

/**
@author qins
@date 2023/6/7
@desc 阿里云模板短信
 */
class AliyunSmsTemplate(private var smsProperties: SmsProperties) : SmsTemplate {

    private val client: Client

    init {
        val config = Config()
            .setAccessKeyId(smsProperties.accessKeyId)
            .setAccessKeySecret(smsProperties.accessKeySecret)
            .setEndpoint(smsProperties.endpoint)
        this.client = Client(config)
    }

    override fun send(phones: String, templateId: String, param: Map<String, String>?) {
        if(!smsProperties.enable) {
            throw BaseException(-1, "系统未开启短信发送功能")
        }
        if(phones.isBlank()) {
            throw BaseException(-1, "手机号不能为空")
        }
        if(templateId.isBlank()) {
            throw BaseException(-1, "短信模板不能为空")
        }
        val req = SendSmsRequest()
            .setPhoneNumbers(phones)
            .setSignName(smsProperties.signName)
            .setTemplateCode(templateId)
            .setTemplateCode(templateId)
            .setTemplateParam(JSONUtil.toJsonStr(param))
        try {
            val response = client.sendSms(req)
            if("OK" != response.getBody().getCode()) {
                throw BaseException(-1, response.getBody().getMessage())
            }
        } catch (e: Exception) {
            throw BaseException(-1, e.message ?: "")
        }
    }
}